<template>
  <div id="Userpage">
    <div class="personal-card">
      <el-avatar
        shape="circle"
        :size="200"
        :fit="fit"
        :src="User.avator"
      />
      <button @click="handleButtonClick()">修改头像</button>
      <input ref="fileInputRef" type="file" style="display: none" @change="handleFileChange()" />
      <h1 class="name">{{User.username}}</h1>
      <p class="occupation">Web Developer</p>
      <div class="social-links">
        <a href="#" class="social-link">
          <i class="fab fa-github"></i>
        </a>
        <a href="#" class="social-link">
          <i class="fab fa-linkedin"></i>
        </a>
      </div>
      <p class="like-count">被点赞总数: {{User.support}}</p>
      <p class="personal-signature-container">
        <span class="personal-signature">个人签名: {{User.personalSignature}}</span>
        <button class="edit-signature-btn" @click="openEditSignatureDialog()">修改</button>
      </p>
      <p class="followed-forum">发过的帖子:</p>
      <div v-for="(post, postIndex) in userPostList" :key="postIndex">
        <el-avatar
          shape="circle"
          :size="80"
          :fit="fit"
          :src="User.avator"
        />
        {{ post.title }}
        <div v-html="post.postContent"></div>
      </div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="userPostList.length"
      >
      </el-pagination>
      <button class="private-message-btn" @click="ToMessage()" v-if="IsMessage">私信</button>

      <el-dialog
        v-model="editSignatureDialogVisible"
        title="修改个人签名"
        width="30%"
      >
        <template #content>
          
        </template>
        <template #footer>
          <el-input v-model="newSignature" placeholder="请输入新的个人签名">123</el-input>
          <span class="dialog-footer">
            <el-button @click="editSignatureDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveSignature()">保存</el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog
        v-model="toMessageDialogVisible"
        title="发私信"
        width="30%"
      >
        <template #content>
          
        </template>
        <template #footer>
          <el-input v-model="newMessage" placeholder="请输入消息"></el-input>
          <span class="dialog-footer">
            <el-button @click="editSignatureDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="sendMessage()">发送</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import axios from 'axios';
import { onMounted, ref ,} from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { userConfig,config } from '@/config/config';

const socket = ref(null);
const route = useRoute();
const router = useRouter();
let userid = route.query.user;
let userDto = ref({
  id: "",
  username: "",
  password: "",
  number: ""
});
let User = ref({
  personalSignature: '代码改变世界'
});
let IsMessage = ref(true);
let userPostList = ref([]);
const fit = 'cover';
const currentPage = ref(1);
const pageSize = ref(5);
const currentPagePosts = ref([]);
const editSignatureDialogVisible = ref(false);
const newSignature = ref('');
const fileInputRef = ref(null);
let QiniuToken=ref('')
let toMessageDialogVisible=ref(false)
let newMessage=ref('')

onMounted(() => {
  getUser();
  getUserPostList();
  updateCurrentPagePosts();
});

const getUser = async () => {
  userDto.value.id = route.query.user;
  await axios.post("api/user/getUser", userDto.value,config).then(function (response) {
    User.value = response.data.data;
    console.log(User.value);
  });
  if (localStorage.getItem("userId") == route.query.user) {
    IsMessage.value = false;
    console.log("IsMessage:" + IsMessage.value);
  }
};

function ToMessage() {
  toMessageDialogVisible.value=true
  socket.value = new WebSocket('ws://localhost:8080/chat');

socket.value.addEventListener('open', () => {
  socket.value.send("userId:"+localStorage.getItem("userId"))
  console.log('连接已建立');
})
}
const getUserPostList = async () => {
  await axios.post("api/posts/getUserPostList", userDto.value,config)
  .then(function (response) {
    userPostList.value = response.data.data;
    console.log("userPostList:" + userPostList.value);
    
  });

};

const updateCurrentPagePosts = () => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  currentPagePosts.value = userPostList.value.slice(startIndex, endIndex);
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  updateCurrentPagePosts();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  updateCurrentPagePosts();
};

const openEditSignatureDialog = () => {
  newSignature.value = User.value.personalSignature;
  editSignatureDialogVisible.value = true;
};

const saveSignature =async() => {
  try {
    console.log(newSignature.value)
    // 这里需要替换为实际的更新签名的 API 接口
    User.value.personalSignature=newSignature.value
    await axios.post('api/user/updateSignature', User.value,config).then(function(response){
      console.log(response.status)
      editSignatureDialogVisible.value = false;
    });
   
  } catch (error) {
    console.log(User)
    console.error('更新签名失败:', error);
  }
};

const sendMessage=()=>{
  const fullMessage = `${userDto.value.id}:${newMessage.value}:${localStorage.getItem("userId")}`;
  socket.value.send(fullMessage);
  newMessage.value=''
  toMessageDialogVisible.value=false
}

// 从后端获取上传凭证的函数，这里假设你有一个后端接口可以返回 token
const getUploadToken = async () => {
  try {
    const response = await axios.post('api/user/getQiniuToken',userDto,config)
    console.log(response)
    return response.data.data
    
  } catch (error) {
    console.error('获取上传凭证失败:', error);
    return null;
  }
};

// 上传头像到七牛云的函数
const uploadAvatarToQiniu = async (file) => {
  const token = await getUploadToken();
  QiniuToken.value=token;
  if (!token) {
    console.log("没有token",token)
    return;
  }

  const formData = new FormData();
  formData.append('token', token);
  formData.append('file', file);

  try {
    const response = await axios.post('https://up-z2.qiniup.com', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    console.log('上传到七牛云成功:', response.data);
    return response.data.key;
  } catch (error) {
    console.error('上传到七牛云失败:', error);
    return null;
  }
};

// 将图片地址发送给后端的函数
const sendAvatarUrlToBackend = async (url) => {
  try {
    User.value.avator=url
    const response = await axios.post('api/user/changeAvater', User.value);
    console.log('头像地址发送给后端成功:', response.data);
    window.location.reload();
    return response.data;
  } catch (error) {
    console.error('头像地址发送给后端失败:', error);
    return null;
  }
};

// 处理按钮点击事件
const handleButtonClick = () => {
  fileInputRef.value.click();
};

// 处理文件选择事件
const handleFileChange = async () => {
  const file = fileInputRef.value.files[0];
  console.log("选择文件已触发")
  if (file) {
    console.log("已找到文件")
    const qiniuKey = await uploadAvatarToQiniu(file);
    if (qiniuKey) {
      console.log("开始上传")
      const domain = 'http://svftekle7.hn-bkt.clouddn.com'; // 替换为你的七牛云存储空间域名
      const avatarUrl = `${qiniuKey}`;
      await sendAvatarUrlToBackend(avatarUrl);
    }
  }
};
</script>

<style scoped>
#Userpage {
  background-color: #F0F8FF;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.personal-card {
  background-color: #FFFFFF;
  border-radius: 20px;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 80%;
  max-width: 600px;
  text-align: center;
  position: relative;
  overflow: hidden;
}

.personal-card::before {
  content: "";
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: linear-gradient(45deg, #FF69B4, #87CEFA);
  z-index: -1;
  opacity: 0.1;
  transform: rotate(-10deg);
}

.el-avatar {
  border: 8px solid #FF69B4;
  margin-bottom: 20px;
}

.name {
  font-size: 36px;
  font-weight: bold;
  color: #FF1493;
  margin-bottom: 10px;
}

.occupation {
  font-size: 18px;
  color: #666;
  margin-bottom: 20px;
}

.social-links {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-bottom: 30px;
}

.social-link {
  color: #87CEFA;
  font-size: 24px;
  transition: color 0.3s ease;
}

.social-link:hover {
  color: #00BFFF;
}

.like-count,
.personal-signature-container {
  font-size: 16px;
  color: #333;
  margin-bottom: 15px;
}

.personal-signature {
  margin-right: 10px;
}

.edit-signature-btn {
  background-color: #87CEFA;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 5px 10px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.edit-signature-btn:hover {
  background-color: #00BFFF;
}

.followed-forum {
  font-size: 16px;
  color: #333;
  font-weight: bold;
  margin-bottom: 15px;
}

.personal-card div[class*="post"] {
  background-color: #F5F5F5;
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 20px;
  text-align: left;
}

.personal-card div[class*="post"] el-avatar {
  border-width: 4px;
  margin-right: 15px;
  vertical-align: middle;
}

.private-message-btn {
  background-color: #FF69B4;
  color: #FFFFFF;
  border: none;
  border-radius: 30px;
  padding: 15px 30px;
  font-size: 18px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.private-message-btn:hover {
  background-color: #FF1493;
}

.el-pagination {
  margin-top: 20px;
}
</style>    